<script setup>
import { ref, onMounted } from 'vue'
import {
  getListLinesService,
  DelRoutes,
  AuditService,
  CommendService
} from '@/api/line.js'
import { Edit, Delete, Document, Check, Close } from '@element-plus/icons-vue'
import { formatTime2 } from '@/utils/format.js'
import LineEdit from './components/LineEdit.vue'
import DetailList from './components/DetailList.vue'
const detailRef = ref()
const loading = ref(false)
const showRef = ref()
const defaultParams = ref({
  id: null,
  pageNum: 1,
  pageSize: 10,
  routeMileage: '',
  routeName: '',
  routeStatus: null,
  routeTags: [],
  spendTime: null,
  suitableTime: '',
  userId: null,
  alongScenicAreaVO: [],
  scenicAreaStart: '',
  scenicAreaEnd: '',
  routeImages: [],
  routeImage: [],
  alongScenicArea: [],
  createRouteUserAccount: '',
  routeElements: []
})
const params = ref({
  id: null,
  pageNum: 1,
  pageSize: 10,
  routeMileage: '',
  routeName: '',
  routeStatus: null,
  routeTags: [],
  spendTime: null,
  suitableTime: '',
  userId: null,
  alongScenicAreaVO: [],
  scenicAreaStart: '',
  scenicAreaEnd: '',
  routeImages: [],
  routeImage: [],
  createRouteUserAccount: '',
  alongScenicArea: [],
  routeElements: []
})
const total = ref(0)
const isloading = ref(false)
const dataList = ref([])
//检验规则
const rules = {
  suitableTime: [
    { required: false, message: '请输入适宜时间', trigger: 'blur' },
    {
      pattern: /^\d{1,10}$/,
      message: '适宜时间必须为1-10的数字',
      trigger: 'blur'
    }
  ]
}
const getRoutesList = async () => {
  isloading.value = true

  const res = await getListLinesService(params.value)
  console.log('res', res)
  dataList.value = res.data.data.records
  total.value = res.data.data.total
  isloading.value = false
}

// 编辑
const onEditRoutes = (row) => {
  showRef.value.open(row)
  console.log('编辑', row)
}
// 审核
const OnAudit = async (row) => {
  console.log(row)
  let id = row.id

  const params = new URLSearchParams()
  params.append('id', id)
  console.log(params)
  const res = await AuditService(params)
  // console.log('res', res)
  if (res.data.code == 200) {
    ElMessage.success('审核成功')
    getRoutesList()
  } else {
    ElMessage.error('审核失败')
  }
}
// 添加
const onAdd = () => {
  showRef.value.open({})
  console.log('添加')
}
const onSuccess = () => {
  const lastPage = Math.ceil((total.value + 1) / params.value.pageSize)
  params.value.pageNum = lastPage
  getRoutesList()
}
//删除
const onDelRoutes = async (row) => {
  let ids = row.id
  console.log('ids', ids)
  try {
    await ElMessageBox.confirm('是否要删除', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    if (!Array.isArray(ids)) {
      ids = [ids]
    }
    console.log('Before calling DelRoutes')
    await DelRoutes(ids) // 确保 DelRoutes 返回的是一个 Promise
    console.log('After calling DelRoutes')
    ElMessage.success('删除成功')
    getRoutesList() // 在删除操作成功后调用 getRoutesList
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 点击后显示详情
const getDetails = (row) => {
  console.log('详情', row)
  detailRef.value.open(row)
}

// 重置
const onReset = () => {
  params.value = { ...defaultParams }
  params.value.pageNum = 1 // 重置页面
  getRoutesList()
}
const onSearch = async () => {
  // console.log('search')
  loading.value = true
  console.log('params', params.value)
  const res = await getListLinesService({ ...params.value })
  if (res.data.data.records && res.data && res.data.data && res) {
    dataList.value = res.data.data.records
    console.log('search', dataList.value)
  } else {
    dataList.value = []
  }
  loading.value = false
}

const onSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  // 基于最新的当前页 和 每页条数，渲染数据
  getRoutesList()
}
const onCurrentChange = (page) => {
  // 更新当前页
  params.value.pageNum = page
  // 基于最新的当前页，渲染数据
  getRoutesList()
}

const GetCommendList = async () => {
  isloading.value = true
  const res = await CommendService()
  dataList.value = res.data.data
  console.log(' dataList.value', dataList.value)
  params.value.pageNum = 1
  total.value = dataList.value.length
}

onMounted(getRoutesList)
</script>
<template>
  <page-container title="线路管理">
    <template #extra>
      <el-button type="primary" @click="GetCommendList"> 推荐线路</el-button>
      <el-button type="primary" @click="onAdd"> 发布线路</el-button>
    </template>
    <!-- 表单位置 -->
    <el-form inline :rules="rules" :model="params">
      <el-form-item label="线路名称" prop="routeName">
        <el-input
          placeholder="请输入线路名称"
          clearable
          v-model="params.routeName"
        />
      </el-form-item>

      <el-form-item label="线路标签" prop="routeTags">
        <el-input
          placeholder="请输入标签"
          clearable
          v-model="params.routeTags"
        />
      </el-form-item>
      <el-form-item label="适宜时间" prop="suitableTime">
        <el-input
          placeholder="请输入适宜时间"
          clearable
          v-model="params.suitableTime"
        />
      </el-form-item>
      <el-form-item label="审核状态" style="width: 300px" prop="routeStatus">
        <el-select
          v-model="params.routeStatus"
          placeholder="请选择审核状态"
          clearable
        >
          <el-option label="未审核" value="0"></el-option>
          <el-option label="已审核" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="onSearch" type="primary">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->

    <el-table :data="dataList" style="width: 100%" v-loading="loading">
      <el-table-column
        label="序号"
        width="100px"
        type="index"
        header-align="center"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="线路名称"
        prop="routeName"
        width="240"
        header-align="center"
        align="center"
      ></el-table-column>

      <el-table-column
        label="线路标签"
        prop="routeTags"
        width="260"
        header-align="center"
        align="center"
      >
      </el-table-column>

      <!-- <el-table-column label="创建时间" prop="createTime" width="220">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column> -->
      <el-table-column
        label="创建人"
        prop="createRouteUserAccount"
        width="200px"
        header-align="center"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="线路里程"
        prop="routeMileage"
        width="260"
        header-align="center"
        align="center"
      ></el-table-column>

      <el-table-column
        label="适宜时间(月)"
        prop="suitableTime"
        width="200px"
        header-align="center"
        align="center"
      >
        <template #default="{ row }">
          {{ formatTime2(row.suitableTime) }}
        </template>
      </el-table-column>

      <el-table-column
        label="审核状态"
        prop="routeStatus"
        width="120px"
        header-align="center"
        align="center"
      >
      </el-table-column>

      <el-table-column
        label="操作"
        width="240"
        header-align="center"
        align="center"
      >
        <!-- 作用域插槽 -->
        <template #default="{ row, $index }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="onEditRoutes(row, $index)"
          ></el-button>
          <el-button
            :icon="Document"
            circle
            plain
            type="primary"
            @click="getDetails(row, $index)"
          ></el-button>

          <el-button
            type="primary"
            :icon="Close"
            circle
            plain
            v-if="row.routeStatus == 0"
            @click="OnAudit(row, $index)"
          ></el-button>
          <el-button
            type="primary"
            v-if="row.routeStatus == 1"
            :icon="Check"
            circle
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="onDelRoutes(row, $index)"
          ></el-button>
        </template>
      </el-table-column>

      <!--  可以定制empty插槽 -->
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[2, 3, 5, 10]"
      :background="true"
      layout="jumper, total, sizes, prev, pager, next"
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <line-Edit ref="showRef" @success="onSuccess"></line-Edit>
    <detail-list ref="detailRef"></detail-list>
  </page-container>
</template>
<style lang="scss" scoped></style>
